package com.aiwei.tdjk.service.impl;

import com.aiwei.tdjk.dao.extend.OrganizationExtendMapper;
import com.aiwei.tdjk.entity.Organization;
import com.aiwei.tdjk.entity.OrganizationExample;
import com.aiwei.tdjk.service.OrganizationService;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by yanfeng on 2016/12/13.
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    private OrganizationExtendMapper organizationExtendMapper;

    @Override
    public Set<Long> findAncestorIds(Iterable<Long> currentIds) {
        Set<Long> parents = Sets.newHashSet();
        for (Long currentId : currentIds) {
            parents.addAll(findAncestorIds(currentId));
        }
        return parents;
    }
    //todo  优化
    @Override
    public Set<Long> findAncestorIds(Long currentId) {
        Set ids = Sets.newHashSet();
        Organization organization = organizationExtendMapper.selectByPrimaryKey(currentId);

        if (organization == null) {
            return ids;
        }
        for (String idStr : StringUtils.tokenizeToStringArray(organization.getParentIds(), "/")) {
            if (!StringUtils.isEmpty(idStr)) {
                ids.add(Long.valueOf(idStr));
            }
        }
        return ids;
    }

    /**
     * 过滤仅获取可显示的数据
     *
     * @param organizationIds
     * @param organizationJobIds
     */
    public void filterForCanShow(Set<Long> organizationIds, Set<Long[]> organizationJobIds) {

        Iterator<Long> iter1 = organizationIds.iterator();

        while (iter1.hasNext()) {
            Long id = iter1.next();
            Organization o = organizationExtendMapper.selectByPrimaryKey(id);
            if (o == null || Boolean.FALSE.equals(o.getIsShow())) {
                iter1.remove();
            }
        }

        Iterator<Long[]> iter2 = organizationJobIds.iterator();

        while (iter2.hasNext()) {
            Long id = iter2.next()[0];
            Organization o = organizationExtendMapper.selectByPrimaryKey(id);
            if (o == null || Boolean.FALSE.equals(o.getIsShow())) {
                iter2.remove();
            }
        }

    }

    /**
     * 根据主键id获取元素
     *
     * @param id
     * @return
     */
    @Override
    public Organization get(long id) {
        return organizationExtendMapper.selectByPrimaryKey(id);
    }

    /**
     * 更新节点
     *
     * @param organization
     */
    @Override
    public void update(Organization organization) {
        String str = organization.getParentIds();
        boolean lang= organization.getIsShow();
        if (!lang) {
            updateChildIsShow(lang,str + organization.getId());
        } else {
            while (str!=""){
                str=getSubStr(str);
                if(str.equals("")) break;
                updateChildIsShow(lang,str);
            }
        }
        organizationExtendMapper.updateByPrimaryKeySelective(organization);
    }
    public String getSubStr(String str) {
        str=str.substring(0,str.lastIndexOf("/"));
        str=str.substring(0,str.lastIndexOf("/")+1);
        return str;
    }

    /**
     * 查询all组织机构
     *
     * @return
     */
    @Override
    public List<Organization> findAllWithSort(boolean isShow) {
        OrganizationExample example = new OrganizationExample();
        if (isShow) {
            example.or().andIsShowEqualTo(true);
        } else {
            example.or();
        }
        return organizationExtendMapper.selectByExample(example);
    }

    /**
     * 根据名称模糊查询组织机构
     *
     * @param name
     * @return
     */
    @Override
    public List<Organization> findAllByName(String name) {
        return organizationExtendMapper.findAllByName(name);
    }

    /**
     * 根据查询组织机构的下级机构
     *
     * @param models
     * @return
     */
    @Override
    public List<Organization> findChildren(List<Organization> models) {
        return null;
    }

    /**
     * 新增子节点
     *
     * @param parentId
     * @param child
     */
    @Override
    public void appendChild(long parentId, Organization child) {

        child.setParentId(parentId);
        Organization parent = organizationExtendMapper.selectByPrimaryKey(parentId);
        child.setParentIds(parent.getParentIds() + parent.getId() + "/");
        child.setWeight(nextWeight(parent.getId()));
        organizationExtendMapper.insertSelective(child);
    }

    /**
     * 删除节点
     *
     * @param id
     */
    @Override
    public void delete(long id) {
        organizationExtendMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteSelfAndChild(long id, String makeSelfAsNewParentIds) {
        organizationExtendMapper.deleteSelfAndChild(id, makeSelfAsNewParentIds);
    }

    //"select case when max(weight) is null then 1 else (max(weight) + 1) end from %s where parentId = ?1"
    public int nextWeight(long id) {
        OrganizationExample example = new OrganizationExample();
        example.or().andParentIdEqualTo(id);
        example.setOrderByClause("weight Desc");
        List<Organization> organizations = organizationExtendMapper.selectByExample(example);
        if (organizations.isEmpty()) {
            return 1;
        } else {
            return organizations.get(0).getWeight() + 1;
        }
    }

    /**
     * 修改子节点状态
     *
     * @param parentIds
     * @return
     */
    public void updateChildIsShow(boolean isShow,String parentIds) {
        Organization organization =new Organization();
        organization.setIsShow(isShow);
        organization.setParentIds(parentIds);
        organizationExtendMapper.updateChildIsShow(organization);
    }


}
